package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

const appid = "wxe6afe277f2a07a63"
const secret = "ad3046e80fe8f7b408e5c824ea23dc7e"

func main() {
	//TokenDemo()

	UserPhoneDemo()

}

func TokenDemo() {
	at := NewAccessToken(appid, secret)

	token, err := at.GetStableAccessToken()
	if err != nil {
		return
	}

	fmt.Println("token:", token.AccessToken)
}

func UserPhoneDemo() {

	http.HandleFunc("/get_user_phone", func(w http.ResponseWriter, r *http.Request) {
		var err error
		defer func() {
			if err != nil {
				log.Println("执行失败", err)
				http.Error(w, "执行失败", http.StatusInternalServerError)
			}
		}()

		body, err := io.ReadAll(r.Body)
		if err != nil {
			return
		}

		params := &struct {
			Code string `json:"code,omitempty"`
		}{}
		err = json.Unmarshal(body, params)
		if err != nil {
			return
		}

		tokenEntity, err := NewAccessToken(appid, secret).GetStableAccessToken()
		if err != nil {
			return
		}
		userInfo, err := NewUser().GetUserPhoneNumber(params.Code, tokenEntity.AccessToken)
		if err != nil {
			return
		}

		resp := struct {
			Code int32                  `json:"code,omitempty"`
			Msg  string                 `json:"msg,omitempty"`
			Data map[string]interface{} `json:"data"`
		}{
			Code: 200,
			Msg:  "success",
			Data: map[string]interface{}{"phone": userInfo.PhoneInfo.PhoneNumber},
		}
		respByte, err := json.Marshal(resp)
		if err != nil {
			return
		}

		_, err = w.Write(respByte)
	})

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("Listen Server Fail: ", err)
		return
	}
}
